<template>
  <div class="pagebox">
    <div class="topFiltrate bg">
      <p
        v-for="(item, index) in dataList"
        :key="index"
        @click="changedate(index)"
        :class="dateType == index ? 'activep' : ''"
        class="colorin"
      >
        {{ item }}
        <a-range-picker
          v-if="index === 4"
          v-model="rangeDate"
          :format="dateFormatList"
          :disabled-date="disabledDate"
          @change="ondateChange"
        />
      </p>
    </div>
    <div class="app-container aCnopadding">
      <a-row :gutter="10">
        <a-col :span="7">
          <a-row>
            <!-- 设备数量 -->
            <EquipmentNumber :alarmStatues="eqmColors" :StateCountData="StateCountData" />
          </a-row>
          <a-row>
            <!-- 状态统计 -->
            <StateStatistics :alarmStatues="alarmStatues" :SumStateTimeList="SumStateTime" />
          </a-row>
        </a-col>
        <!-- 加工信息 -->
        <a-col :span="11">
          <ProcessingInformation :AllProduce="AllProduce" />
        </a-col>
        <!-- 报警分析 -->
        <a-col :span="6">
          <!-- <ToolFile /> -->
          <AlarmAnalysis :AlarmList="AlarmList" />
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <!-- 效率分析 -->
        <a-col :span="7">
          <EfficiencyAnalysis :chartData="chartData" @onTabChange="efficiencyonTabChange" />
        </a-col>
        <!-- 生产统计 -->
        <a-col :span="9">
          <ProductionFigures :productrank="productrank" :timerank="timerank" />
        </a-col>
        <!-- 产量统计 -->
        <a-col :span="8">
          <ProducStatistics :chartDatalineobj="chartDataline" />
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import '@/unit/rem';
import { initUserInfo, timeCalculation, formatCurrentMonth, getDayAll, getYearAndMonth } from '@/unit/tool';
import api from '@/api/workshop';
import eapi from '@/api/equipment';
import EquipmentNumber from './components/equipmentNumber/index.vue';
import StateStatistics from './components/stateStatistics/index.vue';
import EfficiencyAnalysis from './components/efficiencyAnalysis/index.vue';
import ProductionFigures from './components/productionFigures/index.vue';
import ProducStatistics from './components/producStatistics/index.vue';
import AlarmAnalysis from './components/alarmAnalysis/index.vue';
import ProcessingInformation from './components/processingInformation/index.vue';
import ToolFile from './components/toolFile/index.vue';
import moment from 'moment';

export default {
  data() {
    return {
      dateType: 0,
      dataList: ['七天', '本月', '半年', '今年', '自定义'],
      rangeDate: null,
      dateFormatList: ['YYYY-MM-DD', 'YYYY-MM-DD'],
      eqmColors: ['#3FC529', '#FBC225', '#E74629', '#E2E7EE'], // 颜色配置项
      alarmStatues: ['#3FC529', '#FBC225', '#E2E7EE'],
      // 设备参数
      params: {
        pageSize: 3,
        pageNum: 1,
        countSort: 'desc',
        startTime: '2021-05-25 00:00:00',
        endTime: '2021-05-25 23:59:59',
        companyId: '3',
      },
      //   设备产量参数
      timeParames: {
        startTime: null,
        endTime: null,
        UserName: null,
        compid: null,
      },
      StateCountData: {}, // 设备数量
      AllProduce: [], // 加工信息
      //   效率分析
      chartData: {
        expectedData: [],
        date: null,
      },
      noTitleKey: 1, // 效率分析当前选中项
      //  生产统计
      productrank: [],
      timerank: [],
      //   状态统计
      SumStateTime: {},
      //   产量统计
      chartDataline: {
        expectedData: [],
        date: null,
      },
      //   报警分析
      AlarmList: [], // 报警分析数据
      timer: null,
    };
  },
  created() {
    this.timeParames.UserName = localStorage.getItem('userName');
    this.timeParames.compid = this.params.companyId = localStorage.getItem('compid');
    this.timeParames.startTime = this.params.startTime = timeCalculation(new Date(), 'subtract', 7) + ' 00:00:00';
    this.timeParames.endTime = this.params.endTime = timeCalculation(new Date(), 'subtract', 1) + ' 23:59:59';
    this.initData();
    initUserInfo(this);
    this.getStateCount();
  },
  mounted() {
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      this.getStateCount();
      this.MacAlarmStatisticByCompId();
      this.getAllProduce();
    }, 30000);
  },
  methods: {
    disabledDate(current) {
      return current && current > moment().startOf('day');
    },
    initData() {
      this.getProduceRank(); //产量排名
      this.gettimeRank();
      this.getSumStateTime(); //某段时间内各个状态的时间统计
      this.getAllProduce();
      console.log(this.dateType);
      if (this.dateType == 3) {
        this.DayProduceSum();
        this.initlineyear();
      } else {
        this.initline();
        this.DayProduceSum();
      }
      this.MacAlarmStatisticByCompId();
    },
    // 获取设备数量
    async getStateCount() {
      const res = await eapi.getGroupCount({
        compid: this.timeParames.compid,
      });
      if (res.MsgCode === 0) {
        let { Data } = res;
        if (Data && Data != null) {
          this.StateCountData = Data;
        }
      }
      // const res = await eapi.CompanyGroupList({
      //   macCompId: '',
      //   Username: this.timeParames.UserName,
      //   compid: this.timeParames.compid,
      // });
      // if (res.MsgCode === '0') {
      //   let { Data } = res;
      //   if (Data && Data.length > 0) {
      //     this.StateCountData = buildData(res.Data);
      //   }
      // }

      function buildData(list) {
        let dataAry = [];
        let stateCountData = { alarm: 0, offline: 0, running: 0, stop: 0 };
        list.forEach((item) => {
          let { MacSNs } = item;
          MacSNs.forEach((ojb) => {
            dataAry.push(ojb);
          });
        });

        dataAry.forEach((item) => {
          let { alarm, offline, running, stop } = stateCountData;
          let { runstate } = item;
          switch (parseInt(runstate)) {
            case 1000:
              stateCountData.running = running + 1;
              break;
            case 2000:
              stateCountData.alarm = alarm + 1;
              break;
            case 3000:
              stateCountData.stop = stop + 1;
              break;
            case 4000:
              stateCountData.offline = offline + 1;
              break;
            default:
              break;
          }
        });
        return { ...stateCountData, all: dataAry.length };
      }
    },
    // 获取机床产量排名
    async getProduceRank() {
      const res = await api.getProduceRank(this.params);
      if (res.msgCode === 0) {
        this.productrank = res.data.rows;
        console.log(res.data.rows,333);
      }
    },
    // 获取机床时间排名
    async gettimeRank() {
      delete this.params.countSort;
      this.params.timeSort = 'desc';
      const res = await api.getProduceRank(this.params);
      if (res.msgCode === 0) {
        this.timerank = res.data.rows;
      }
    },
    // 获取加工信息数据
    async getAllProduce() {
      let parmas = {
        UserName: this.timeParames.UserName,
        companyId: this.timeParames.compid,
        groupId: '-2',
        pageNum: 1,
        pageSize: 50,
      };
      const res = await eapi.getAllProduce(parmas);
      if (res.msgCode === 0) {
        this.AllProduce = res.data.rows;
      }
    },
    // 获取状态统计数据
    async getSumStateTime() {
      let params = {
        companyId: this.params.companyId,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      const res = await api.getSumStateTime(params);
      if (res.msgCode === 0) {
        this.SumStateTime = res.data;
      }
    },
    // 报警分析
    async MacAlarmStatisticByCompId() {
      let params = {
        compId: this.params.companyId,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      const res = await api.MacAlarmStatisticByCompId(params);
      if (res.MsgCode === 0) {
        this.AlarmList = res.Data;
      }
    },

    //折线图
    initline() {
      if (this.noTitleKey == 1) {
        this.GroupOnlineRate(); //开机率
      } else if (this.noTitleKey == 2) {
        this.GroupRunTime(); //运行时间
      } else if (this.noTitleKey == 3) {
        this.GroupAlarmTime();
      }
    },
    //半年折线图
    initlineyear() {
      if (this.noTitleKey == 1) {
        this.HalfYearGroupOnlineRate(); //开机率
      } else if (this.noTitleKey == 2) {
        this.HalfYearGroupRunTime(); //运行时间
      } else if (this.noTitleKey == 3) {
        this.HalfYearGroupAlarmTime(); //故障时间
      }
    },
    //某时间段开机率
    async GroupOnlineRate() {
      const res = await eapi.GroupOnlineRate(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.havelinedata(list, 1, 1);
      }
    },
    //查询时间段内各产线的运行时间（分钟）
    async GroupRunTime() {
      const res = await eapi.GroupRunTime(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.havelinedata(list);
      }
    },
    //查询时间段内各产线的故障时间（分钟）
    async GroupAlarmTime() {
      const res = await eapi.GroupAlarmTime(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.havelinedata(list);
      }
    },
    //查询半年内各产线每月的开机率
    async HalfYearGroupOnlineRate() {
      const res = await eapi.HalfYearGroupOnlineRate(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.havelinedata(list, 'month', 1);
      }
    },
    //查询厂半年内各产线的运行时间（分钟)
    async HalfYearGroupRunTime() {
      const res = await eapi.HalfYearGroupRunTime(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.havelinedata(list, 'month');
      }
    },
    //查询厂半年内各产线的故障时间（分钟）
    async HalfYearGroupAlarmTime() {
      const res = await eapi.HalfYearGroupAlarmTime(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.havelinedata(list);
      }
    },
    //折线图数据转换
    havelinedata(list, time, type) {
      let expectedData = [];
      let name = [];
      let dates = null;
      if (time == 'month') {
        //每月
        let startTime = this.timeParames.startTime.substring(0, 7);
        let endTime = this.timeParames.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.timeParames.startTime, this.timeParames.endTime);
      }
      list.forEach((item) => {
        let data = [];
        dates.forEach((items) => {
          let opt = null;
          if (time == 'month') {
            opt = item.arrayData.find((day) => this.monthcomplement(day.day) == items); //每月
          } else {
            opt = item.arrayData.find((day) => day.day == items); //每天
          }
          if (opt) {
            if (type == 1) {
              data.push((opt.yData * 100).toFixed(2));
            } else {
              data.push((opt.yData / 60).toFixed(2));
            }
          } else {
            data.push(0);
          }
        });
        expectedData.push(data);
        name.push(item.macsn);
      });
      this.chartData.expectedData = expectedData;
      this.chartData.date = dates;
      this.chartData.name = name;
    },
    efficiencyonTabChange(key) {
      this.noTitleKey = key;
      if (this.dateType == 3 || this.dateType == 4) {
        this.initlineyear();
      } else {
        this.initline();
      }
    },
    //时间段内某天的产量
    async DayProduceSum() {
      const res = await eapi.DayProduceSum(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.ProduceSum(list);
      } else {
        this.ProduceSum([]);
      }
    },
    //半年内每月产量
    async HalfYearProduceSum() {
      const res = await eapi.HalfYearProduceSum(this.timeParames);
      if (res.MsgCode === 0) {
        let list = res.Data;
        this.ProduceSum(list, 'month');
      }
    },
    //折线图数据转换
    ProduceSum(list, time) {
      let expectedData = [];
      let dates = null;
      if (time == 'month') {
        //每月
        let startTime = this.timeParames.startTime.substring(0, 7);
        let endTime = this.timeParames.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.timeParames.startTime, this.timeParames.endTime);
      }
      let data = [];
      dates.forEach((items) => {
        let opt = null;
        if (time == 'month') {
          opt = list.find((day) => day.day == items); //每月
        } else {
          opt = list.find((day) => day.day == items); //每天
        }
        if (opt) {
          data.push(opt.num);
        } else {
          data.push(0);
        }
      });
      expectedData.push(data);
      this.chartDataline.expectedData = expectedData;
      this.chartDataline.date = dates;
      this.chartDataline.name = ['产量'];
    },
    // 自定义时间变化回调
    ondateChange(dates, datestring) {
      this.timeParames.startTime = datestring[0];
      this.timeParames.endTime = datestring[1];
      this.params.startTime = datestring[0] + ' 00:00:00';
      this.params.endTime = datestring[1] + ' 23:59:59';
      this.initData();
    },
    // 日期选中事件
    changedate(i) {
      this.dateType = i;
      switch (i) {
        case 0:
          // 最近7天
          this.timeParames.endTime = timeCalculation(new Date(), 'subtract', 0);
          this.timeParames.startTime = timeCalculation(new Date(), 'subtract', 6);
          this.params.endTime = timeCalculation(new Date(), 'subtract', 1) + ' 00:00:00';
          this.params.startTime = timeCalculation(new Date(), 'subtract', 7) + ' 23:59:59';
          this.initData();
          break;
        case 1:
          // 本月
          this.timeParames.startTime = formatCurrentMonth('start', 0);
          this.timeParames.endTime = formatCurrentMonth('end', 0);
          this.params.startTime = formatCurrentMonth('start', 0) + ' 00:00:00';
          this.params.endTime = formatCurrentMonth('end', 0) + ' 23:59:59';
          this.initData();
          break;
        case 2:
          // 最近半年
          this.timeParames.startTime = formatCurrentMonth('start', -5);
          this.timeParames.endTime = timeCalculation(new Date(), 'subtract', 0);
          this.params.startTime = formatCurrentMonth('start', -5) + ' 00:00:00';
          this.params.endTime = timeCalculation(new Date(), 'subtract', 0) + ' 23:59:59';
          this.initData();
          break;
        case 3:
          // 一年
          let time = formatCurrentMonth('end', 0);
          this.timeParames.startTime = time.substring(0, 4) + '-01-01';
          this.timeParames.endTime = timeCalculation(new Date(), 'subtract', 0);
          this.params.startTime = time.substring(0, 4) + '-01-01' + ' 00:00:00';
          this.params.endTime = timeCalculation(new Date(), 'subtract', 0) + ' 23:59:59';
          this.initData();
          return;
      }
    },
    // /格式化年月不带0的
    monthcomplement(val) {
      let month = val.split('-');
      let monthnum = month[1] <= 9 ? '0' + month[1] : month[1];
      let num = month[0] + '-' + monthnum;
      return num;
    },
  },
  components: {
    EquipmentNumber,
    StateStatistics,
    EfficiencyAnalysis,
    ProductionFigures,
    ProducStatistics,
    AlarmAnalysis,
    ProcessingInformation,
    ToolFile,
  },
  destroyed() {
    clearInterval(this.timer);
  },
};
</script>

<style lang="less" scoped>
@import './light.less';
@import './style';
</style>
